<?php



namespace App\Models\Traits;

use Bouncer;
use App\Models\Userinfo;

/**
 *
 * @author Administrator
 */
trait HasUser {
    
    protected static function bootHasUser()
    {

		static::saving(function ($model) {
			$data = static::getCompanyData();
			$model->fill($data);
        });
		
		static::creating(function ($model) {
			$data = static::getCompanyData();
			$model->fill($data);
        });
		
		static::saved(function ($model) {
			$userid = $model->userid;
			
			$data = app('request')->only(['userphone', 'Co_ID']);

			Userinfo::updateOrCreate(
			['userid'=>$userid],
			$data
			);

        });
		
		static::created(function ($model) {
			$userinfo = $model->userinfo();
			$data = app('request')->all();
			$userinfo->create($data);
        });
		
		static::deleted(function ($model) {
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
                return;
            }

            $model->userinfo()->delete();
        });
    }
	
	protected static function getCompanyData() {
		//$user = $request->user();
		$data = app('request')->only('Co_ID');
		$user = auth()->user();
		$isSuper = $user->isSuper();

		if (!$isSuper) {
			$data['Co_ID'] = $user->Co_ID;
		}
		if(array_get($data, 'Co_ID')){
		   Bouncer::scope()->onlyRelations(); 
		   Bouncer::scope()->to($data['Co_ID']);
		}
		return $data;
	}
}
